/**
 * @license j2w.apply.js
 * Adds apply button functionality to the base j2w object.
 *
 * Jobs2Web, INC CONFIDENTIAL
 * ------------------
 * Copyright 2003-2012 Jobs2Web, Inc
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remain the property of
 * Jobs2web, Inc and its suppliers, if any. The intellectual and
 * technical concepts contained herein are proprietary to Jobs2Web, Inc
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from
 * Jobs2Web, Inc.
 *
 * @extends j2w.core.js
 *
 */

var j2w = j2w || {};

j2w.Apply = (function () {
    "use strict";

    // *** PRIVATE ************************************************************

    var _args = {},
        _bHasBeenInitted = false,
        _preApplyServiceURL = '/services/applycontroller/apply/',

        // *** METHODS

        _init = function (args) {
            if (!_bHasBeenInitted) {
                _args = args;

                return (_bHasBeenInitted = true);
            } else {
                return false;
            }
        };

        // *** METHODS



    // *** PUBLIC *************************************************************

    return {
        init : function (args) {
            return _init(args);
        },

        // *** NAMESPACED DEFAULT COLLECTIONS *********************************

        // *** Args - Initialization Arguments ********************************

        Args : {
            get : function (argName) {
                return j2w.Args.get(argName, _args);
            }
        },

        // *** OTHER METHODS **************************************************

        getPreApplyServiceURL : function () {
            return _preApplyServiceURL;
        },

        // applyDestinationHelper()
        // Applies options to the apply redirect URL.
        applyDestinationHelper : function (redirURL, options) {
            var aParams = [],
                queryString = '';

            if (typeof options.method === 'string') {
                switch (options.method) {
                    case 'linkedin':
                        if (typeof options.email === 'string') {
                            aParams.push('email=' + options.email);
                            aParams.push('reviewtoken=AwL');
                            aParams.push('socialSrc=li');
                        }

                        break;
                    default:
                        break;
                }
            }

            if (aParams.length) {
                // Create a partial query string by combining array elements into a string.
                queryString = aParams.join('&');

                // Set ? or & as the first character of the query string, depending on if ? already exists or not.
                if (redirURL.indexOf('?') === -1) {
                    queryString = '?' + queryString;
                } else {
                    queryString = '&' + queryString;
                }

                // Put the query string in the right place, if a URL fragment is present.
                if (redirURL.indexOf('#') !== -1) {
                    aTmp = redirURL.split('#');
                    redirURL = aTmp[0] + queryString + '#' + aTmp[1];
                } else {
                    redirURL = redirURL + queryString;
                }

                // Final clean-up.
                if (redirURL.indexOf('?&') !== -1) {
                    redirURL = redirURL.replace('?&', '?');
                }
            }

            // Return the options-modified redirect URL.
            return redirURL;
        },

        // countApplyGoToJob
        // Records a user's apply and goes to the job.
        countApplyGoToJob : function (applyType, jobID) {
            j2w.xhrRequest = $.ajax({
                type     : 'GET',
                url      : '/services/user/apply',
                data     : { jobid : jobID },
                dataType : 'json',
                error: function (xhr, textStatus, errorThrown) {
                    j2w.Apply.recoverFromAjaxError(xhr);
                },
                success: function (data) {
                    j2w.Apply.setApplyID(data.applyid);

                    j2w.Apply.goToJob();
                }
            });
        },

        // goToApply()
        // Sends the user to apply to a job.
        goToApply : function (_redirect, options, jobID) {
            if (jobID !== null) {
                var redirect = (typeof _redirect === 'boolean' && _redirect === true) ? true : false;
                var redirURL = '',
                    appendURL = '/talentcommunity/apply/' + jobID + '/';

                // Add locale.
                if (j2w.Apply.Args.get('locale') && j2w.Apply.Args.get('locale').length) {
                    appendURL += '?locale=' + j2w.Apply.Args.get('locale');
                }
                
                // Add tracking.
                appendURL += '#tracked';

                // Switch to https, if we're not there already.
                redirURL = j2w.Util.needToSwitchToSSL() ? 'https://' + window.location.host + appendURL : appendURL;

                // If options were passed in, apply them to the redirect URL.
                if (typeof options === 'object') {
                    redirURL = applyDestinationHelper(redirURL, options);
                }

                // If redirect is true, go to the apply url, but remove the forwarding page from the browser history.
                // The user should not be able to go back to the forwarding page.
                redirect ? window.location.replace(redirURL) : window.location.assign(redirURL);
            }
        },

        // goToJob()
        // Determines how to get to the ATS, and sends the user there.
        goToJob : function () {
            var aURLVars = [],
                exitURL = j2w.Apply.getPreApplyServiceURL();

            // Modifies the exit URL with an apply ID, if available, or job ID.
            if (typeof j2w.applyID === 'number') {
                aURLVars.push('applyid=' + j2w.applyID);
            } else if (j2w.Apply.Args.get('jobID')) {
                aURLVars.push('jobid=' + j2w.Apply.Args.get('jobID'));
            }

            // Pass the social source along, if defined.
            if (window.attributes && window.attributes.socialsrc) {
                aURLVars.push('applytype=' + j2w.Util.networkMap(window.attributes.socialsrc));
            } else {
                aURLVars.push('applytype=standard');
            }

            // Include URL params in the URL, if there were any to be included.
            if (aURLVars.length) {
                exitURL += '?' + aURLVars.join('&');
            }

            document.location.href = exitURL;
        },

        // handleApplyNowButton()
        // Handles an apply now button click event.
        handleApplyNowButton : function (event) {
            // We might be calling this function based on a non-event, in which case "event" is really an options object, and not a real event.
            var options = typeof event.handler === 'undefined' && typeof event.custom === 'boolean' && event.custom === true ? event : undefined;

            j2w.Util.eventPreventer(event);

            // If the user has cookies enabled, do a regular apply. If not, the default href of the button is used.
            if ($.cookies.test()) {
                if (j2w.Apply.Args.get('jobID')) {
                    if (!window.j2w.applyInProgress) {
                        // Indicate that an apply is in process and that subsequent apply now clicks should be ignored.
                        window.j2w.applyInProgress = true;

                        // Now that it's OK to proceed, let's go ahead and track the apply in Google Analytics.
                        if (typeof $gaApply !== 'undefined') {
                            TrackGoogleAnalytics(
                                $gaApply.link,
                                $gaApply.id,
                                $gaApply.value,
                                $gaApply.name,
                                $gaApply.group,
                                $gaApply.site
                            );
                        }

                        // Is this site configured to use the Talent Community?
                        if (j2w.Apply.Args.get('subscribeAtApply')) {
                            var applyDataJobID = j2w.Apply.Args.get('jobID');

                            // Go the the Talent Community only if the user's credentials are not valid, or if the user is new.
                            j2w.xhrRequest = $.ajax({
                                type     : 'GET',
                                url      : '/services/security/loginstatus/',
                                dataType : 'json',
                                error: function (xhr, textStatus, errorThrown) {
                                    j2w.Apply.recoverFromAjaxError(xhr);
                                },
                                success: function (oResult) {
                                    // The path varies depending on whether the user is a valid, logged in user or not.
                                    if (!oResult.success) {
                                        // For people who aren't logged in, present the SSO login or direct them to the Talent Community.
                                        if (j2w.SSO && j2w.SSO.isEnabled() && j2w.SSO.ready) {
                                            j2w.SSO.showStack('viewRMPLogin');
                                        } else {
                                            j2w.Apply.goToApply(false, options, j2w.Apply.Args.get('jobID'));
                                        }
                                    } else {
                                        var applyType = '';

                                        if (typeof options === 'object') {
                                            applyType = (typeof options.method === 'string' && options.method === 'linkedin') ? 'linkedin' : 'default';
                                        }

                                        // Since the user is already logged in, track the apply and go directly to the job.
                                        // Begin SSO, or proceed normally if SSO is not available.
                                        if (j2w.SSO && j2w.SSO.isEnabled() && j2w.SSO.ready) {
                                            j2w.SSO.ssoIDCheck();
                                        } else {
                                            j2w.Apply.countApplyGoToJob(applyType, applyDataJobID);
                                        }
                                    }
                                }
                            });
                        } else {
                            j2w.Apply.goToJob();
                        }
                    }
                }
            } else {
                j2w.Apply.goToJob();
            }
        },

        // recoverFromAjaxError
        // Handles an Ajax error, optionally alerting the user.
        recoverFromAjaxError : function (xhr, customMessage, callback) {
            // Alert the user, unless they aborted a request manually.
            if (xhr.statusText !== 'abort') {
                window.j2w.applyInProgress = false;

                if (typeof customMessage === 'string' && customMessage.length) {
                    alert(customMessage.unescapeHTML());
                } else {
                    alert(jsStr.tcsorrygenericerror.unescapeHTML());
                }
            }

            typeof callback === 'function' ? callback() : null;
        },

        // setApplyID
        //
        setApplyID : function (userApplyID) {
            j2w.applyID = parseInt(userApplyID);
        }
    };
}());

$(function () {
    "use strict";

    // Add startup arguments to the j2w.SSO object if they are not already defined. (Populates jobID, e-mail address, etc.)
    if (typeof startupArgs !== 'object') {
        var startupArgs = {};
    }

    $.extend(j2w.Apply, startupArgs);

    // -------------------------------------------------------
    // EVENT BINDINGS
    // -------------------------------------------------------

        // Go to Talent Community from Apply now >> button

            $('.dialogApplyBtn').click(j2w.Apply.handleApplyNowButton);

            $('.dialogApplyBtn').bind("contextmenu", function (e) {
                return false;
            });
});